<template>
  <div class="position-relative flex column full-height">
    <q-table
      :data="tableData"
      :columns="columns"
      row-key="id"
      class="myTable scroll stick-last-col full-height"
      :loading="tableLoading"
      :pagination="pagination"
      hide-bottom
      separator="cell"
      no-data-label="暂无数据"
      color="primary"
    >
      <template v-slot:header-cell-onLineStatus="props">
        <q-th :props="props">
          {{props.col.label}}
          <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              <div>在线:网关与设备通讯未知，网关与云端服务器通讯正常</div>
              <div>离线:网关与设备通讯未知，网关与云端服务器通讯异常</div>
            </q-tooltip>
          </span>
        </q-th>
      </template>
      <template v-slot:header-cell-connectStatus="props">
        <q-th :props="props">
          {{props.col.label}}
          <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              正常网关连上电源和网络，即为在线。(只有在线状态才能部署网关）
            </q-tooltip>
          </span>
        </q-th>
      </template>
      <template v-slot:header-cell-deploymentStatus="props">
        <q-th :props="props">
          {{props.col.label}}
          <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              部署指将配置信息下发到盒子,只有已部署的网关才能采集到设备信息
            </q-tooltip>
          </span>
        </q-th>
      </template>
      <template v-slot:body-cell-onLineStatus="props">
        <q-td :props="props">
          <div class="living">
            <div class="status" :class="{'offline': props.row.onLineStatus !== 'ONLINE'}"></div>
            {{props.row.onLineStatus === 'ONLINE' ? '在线':'离线'}}
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-connectStatus="props">
        <q-td :props="props">
          <div class="living" v-if="connectStatusObj[props.row.connectStatus]">
            <div class="status" :class="props.row.connectStatus"></div>
            {{ connectStatusObj[props.row.connectStatus]}}
          </div>
          <div v-else>--</div>
        </q-td>
      </template>
      <template v-slot:body-cell-deploymentStatus="props">
        <q-td :props="props">
          <div class="living" v-if="deploymentStatusObj[props.row.deploymentStatus]">
            <div class="status" :class="getDeployStatus(props.row.deploymentStatus)"></div>
            {{ deploymentStatusObj[props.row.deploymentStatus]}}
          </div>
          <div v-else>--</div>
        </q-td>
      </template>
      <template v-slot:header-cell-offPowerTime="props">
        <q-th :props="props">
          {{props.col.label}}
          <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey" style="margin-left: 5px;margin-top: -3px;font-size: 14px" />
            <q-tooltip max-width="500px">
              网关最后上报的外部电源断开时间，用以判断网关离线原因。网关离线时，若最后断电时间早于最后下线时间1分内，则可认为离线原因为外部电源断开；若非1分内，则离线原因可能为网关网络断开，或外部电源实际断开却因网络不好、电容失效等意外导致最后断电时间未成功上报
            </q-tooltip>
          </span>
        </q-th>
      </template>
      <template v-slot:body-cell-deviceCount="props">
        <q-td :props="props">
          <div class="device-count" @click="toDeviceDetail(props.row)">{{props.row.deviceCount}}</div>
        </q-td>
      </template>
      <template v-slot:body-cell-operations="props">
        <q-td class="operations" style="width: 100px">
          <div class="btn-group text-center">
            <q-btn
              style="font-size: 18px"
              flat
              round
              dense
              color="primary"
              @click="goDetail(props.row)"
              class="iconfont icontubiao-113"
            >
              <q-tooltip>详情</q-tooltip>
            </q-btn>
            <q-btn style="font-size: 18px"
                   flat
                   round
                   v-throttle
                   dense
                   color="primary"
                   class="iconfont icontubiao-16"
                   @click="deleteData(props.row)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </div>
        </q-td>
      </template>

    </q-table>

    <div  style="width: 100%;" :style="{'height': noPagination ? '20px' : ''}">
      <pagination
        style="position: relative;padding: 20px"
        v-if="tableData.length > 0 && !noPagination"
        v-model="pagination.page"
        :page-size="pagination.rowsPerPage"
        :total="pagination.rowsNumber"
        @changePage="onPageChange"
        @changePageSize="onPageSizeChange"
      >
      </pagination>
    </div>

    <!-- 设备详情 -->
    <DeviceInfos ref="deviceInfos" />
  </div>
</template>

<script>
import DeviceInfos from './device-infos'
import Pagination from 'src/components/pagination'
import { deploymentStatusObj } from './plc-dialog/constant'
import { deleteBox } from '../../../../boot/miot/list'
import { deleteLatestBox, deletePlcBox } from '../../../../boot/miot/plc-list'
import { controllerTypeObj } from './gateway-dialog/constant'

export default {
  name: 'list-table',
  components: {
    DeviceInfos,
    Pagination
  },
  props: {
    tableLoading: {
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      default: () => []
    },
    connectStatusObj: {
      type: Object,
      default: () => {}
    },
    total: {
      type: Number,
      default: 0
    },
    noPagination: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      columns: [
        { name: 'prodId', label: '网关序列号', align: 'left', field: 'prodId' },
        { name: 'onLineStatus', label: '网关状态', align: 'left', field: 'onLineStatus' },
        { name: 'connectStatus', label: '连接状态', align: 'left', field: 'connectStatus' },
        { name: 'deploymentStatus', label: '部署状态', align: 'left', field: 'deploymentStatus' },
        { name: 'deployedDate', label: '最后部署时间', align: 'left', field: 'deployedDate' },
        { name: 'lastOnlineTime', label: '最后上线时间', align: 'left', field: 'lastOnlineTime' },
        { name: 'lastOfflineTime', label: '最后下线时间', align: 'left', field: 'lastOfflineTime' },
        { name: 'offPowerTime', label: '最后断电时间', align: 'left', field: 'offPowerTime' },
        { name: 'deviceCount', label: '关联设备', align: 'left', field: 'deviceCount' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ],
      // 表格分页配置
      pagination: {
        // 页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      deploymentStatusObj: deploymentStatusObj
    }
  },
  watch: {
    total: {
      immediate: true,
      handler (val) {
        this.pagination.rowsNumber = val
      }
    },
    pagination: {
      deep: true,
      immediate: true,
      handler (val) {
        this.$emit('changePagination', val)
      }
    }
  },
  methods: {
    // 获取部署状态的class
    getDeployStatus (status) {
      const obj = {
        'success': 'online',
        'failed': 'failed',
        'processing': 'inactivated',
        'undeploy': 'offline',
        'timeout': 'failed'
      }
      return obj[status]
    },
    // 跳转到设备详情
    toDeviceDetail (row) {
      const deviceInfo = row.deviceInfo || []
      const result = deviceInfo.map((item, index) => {
        return {
          index: index + 1,
          controllerType: controllerTypeObj[item.isPlc],
          driver: item.driverName,
          deviceName: '',
          deviceNum: item.assetNum,
          device: `${item.deviceName}(${item.assetNum})`
        }
      })
      this.$refs.deviceInfos.showDialog(result)
    },
    /**
     * 跳转到详情页面
     */
    goDetail (info) {
      // const isLatestVersion = info.updateVersion === 2
      const oldVersion = !info.updateVersion
      // 如果不在线的话 就不能跳转了
      if (oldVersion) {
        if (info.onLineStatus !== 'ONLINE') {
          this.$message.warning('设备已离线，请检查网关网络')
          return
        }
        this.$router.push({
          name: 'miotDetail',
          query: {
            boxId: info.boxId,
            deployedDate: info.deployedDate,
            boxStatus: info.boxStatus,
            wanCfg: info.wanCfg ? info.wanCfg.toUpperCase() : '',
            onLineStatus: info.onLineStatus,
            _time: new Date().getTime()
          }
        })
      } else {
        this.$router.push({
          name: 'plcDetail',
          query: {
            boxRemark: info.boxRemark,
            boxId: info.ucloudBoxId,
            deployedDate: info.deployedDate,
            boxNum: info.boxId,
            updateVersion: info.updateVersion,
            offPowerTime: info.offPowerTime,
            _time: new Date().getTime()
          }
        })
      }
    },

    /**
     * 弹框提示是否删除
     */
    deleteData (info) {
      const isLatestVersion = info.updateVersion === 2 || info.updateVersion === 1
      const oldVersion = !info.updateVersion

      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确认要删除此网关信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        // 如果是最新的版本
        if (isLatestVersion) {
          this.deleteLatestDataConfirm(info.boxId, info.ucloudBoxId, info.updateVersion, info.boxTableId)
        } else if (oldVersion) {
          // 如果是最老的版本cnc一对一
          this.deleteDataConfirm(info.boxId)
        }
      })
    },

    /**
     * 执行删除操作
     */
    async deleteDataConfirm (boxId) {
      if (!boxId) return
      const data = await deleteBox(boxId)
      if (data.success) {
        this.$emit('deleteSuccess')
      } else {
        this.$message.error('删除失败')
      }
    },

    /**
     * 执行删除操作
     */
    async deletePlcDataConfirm (boxId, modelType = 0, ucloudBoxId) {
      if (!boxId) return
      await deletePlcBox(boxId, modelType, ucloudBoxId)
      this.$emit('deleteSuccess')
    },

    /**
     * 执行删除操作
     */
    async deleteLatestDataConfirm (boxId, ucloudBoxId, updateVersion, boxTableId) {
      if (!boxId) return
      await deleteLatestBox(boxId, ucloudBoxId, updateVersion, boxTableId)
      this.$emit('deleteSuccess')
    },

    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.$emit('changeData')
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.$emit('changeData')
    },

    // 初始化页面
    initPage () {
      this.pagination.page = 1
    }
  }
}
</script>

<style scoped lang="scss">
.living {
  .status {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: $positive;
  }
  .online {
    background: $positive;
  }
  .inactivated{
    background: $warning;
  }
  .offline {
    background: #666666;
  }
  .failed {
    background: $negative;
  }
}
.device-count{
  color: #5f77fd;
  cursor: pointer;
}
</style>
